package iit.projects.etaxi.view.bean;

import iit.projects.etaxi.model.dto.ReservationSCDO;
import iit.projects.etaxi.model.entity.Reservation;
import iit.projects.etaxi.model.service.ReservationService;
import iit.projects.etaxi.model.service.ServiceLocator;
import iit.projects.etaxi.util.JSFUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.icesoft.faces.component.selectinputdate.SelectInputDate;
import com.icesoft.faces.context.ByteArrayResource;
import com.icesoft.faces.context.Resource;

public class OutputResourceBean{
	
	private ReservationSCDO reservationSCDO;
	private List<Reservation> reservations;
	private Resource imgResource;
	private Resource pdfResource;
	private Resource pdfResourceDynFileName;
	private String fileName = "Choose-a-new-file-name";
	private static final String RESOURCE_PATH = "/WEB-INF/classes/iit/projects/etaxi/view/resources/";
	private String fromCity;
	private SelectInputDate compFromDate;
	private SelectInputDate compToDate;
	private Date fromDate;
	private Date toDate;
	private boolean disabled;
	
	private ServiceLocator serviceLocator;
	private ReservationService reservationService;
	
	public String getFromCity() {
		return fromCity;
	}

	public void setFromCity(String fromCity) {
		this.fromCity = fromCity;
	}

	//String reportFile = "report.jrxml";
	//String reportFile = "taxi_city.jrxml";
	//String reportFile = "taxi_report.jrxml";
	private String reportFile = "taxi_report_count.jrxml";
	
	@javax.annotation.PostConstruct
	public void init(){
		reservationService = serviceLocator.getReservationService();
	}
	
	public void generateReport(ActionEvent event){
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		try{
			Map<String,Date> parameters = new HashMap<String, Date>();
			boolean valid = true;
			//DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		    //Date p_from_time = df.parse("2008/10/01"); 
            
           //Date p_to_time = df.parse("2008/10/31");
			if(fromDate == null){
				JSFUtils.addFacesErrorMessage(compFromDate, UIInput.REQUIRED_MESSAGE_ID);
				valid = false;
			}
			if(toDate == null){
				JSFUtils.addFacesErrorMessage(compToDate, UIInput.REQUIRED_MESSAGE_ID);
				valid = false;
			}
			if(valid)
			{
            parameters.put("p_from_time", fromDate);
            parameters.put("p_to_time", toDate);
            
            JasperDesign jasperDesign = JRXmlLoader.load(context.getResourceAsStream( RESOURCE_PATH + reportFile));
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            Connection jdbcConnection = connectDB("", "", "");
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jdbcConnection);
           
//			OutputResourceBean.runReport("","","",reportFile);
//			imgResource = new ByteArrayResource( toByteArray( context.getResourceAsStream( RESOURCE_PATH + "logo.jpg")));
//			pdfResource =  new ByteArrayResource( toByteArray( context.getResourceAsStream( RESOURCE_PATH + "WP_Security_Whitepaper.pdf")));
//			pdfResourceDynFileName = new ByteArrayResource( toByteArray( context.getResourceAsStream( RESOURCE_PATH + "WP_Security_Whitepaper.pdf")));
			
            
            // added by naveen
            reservationSCDO = new ReservationSCDO();
            reservationSCDO.setStartingDate(fromDate);
            reservationSCDO.setEndingDate(toDate);
			reservations = reservationService.searchReservations(reservationSCDO);
			
			if(this.reservations == null || this.reservations.isEmpty()){
				JSFUtils.addFacesInfoMessage("data.notfound");
				return;
			}
			//.................
					
				pdfResource =  new ByteArrayResource(  JasperExportManager.exportReportToPdf(jasperPrint));
				disabled = true;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	public Resource getImgResource() {
		return imgResource;
	}

	
	public Resource getPdfResource(){
		return this.pdfResource;
	}
	
	public void valueChangeFromDate(ValueChangeEvent event){
		disabled = false;
		pdfResource = null;
	}
	
	public void valueChangeToDate(ValueChangeEvent event){
		disabled = false;
		pdfResource = null;
	}
	
	
	
	public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int len = 0;
        while ((len = input.read(buf)) > -1) output.write(buf, 0, len);
        return output.toByteArray();
    }

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public Resource getPdfResourceDynFileName() {
		return pdfResourceDynFileName;
	}

	public void setPdfResourceDynFileName(Resource pdfResourceDynFileName) {
		this.pdfResourceDynFileName = pdfResourceDynFileName;
	}
	
	 public static Connection connectDB(String databaseName, String userName, String password) {
	        Connection jdbcConnection = null;
	        try{
	            Class.forName("com.mysql.jdbc.Driver");
	            //jdbcConnection = DriverManager.getConnection(databaseName,userName,password);
	           jdbcConnection = DriverManager.getConnection(
	            		"jdbc:mysql://localhost:3306/etaxi", "root", "root");
	        }catch(Exception ex) {
	            String connectMsg = "Could not connect to the database: " + ex.getMessage() + " " + ex.getLocalizedMessage();
	            System.out.println(connectMsg);
	        }
	        return jdbcConnection;
	    }

	public SelectInputDate getCompFromDate() {
		return compFromDate;
	}

	public void setCompFromDate(SelectInputDate compFromDate) {
		this.compFromDate = compFromDate;
	}

	public Date getFromDate() {
		return fromDate;
	}

	public void setFromDate(Date fromDate) {
		this.fromDate = fromDate;
	}

	public SelectInputDate getCompToDate() {
		return compToDate;
	}

	public void setCompToDate(SelectInputDate compToDate) {
		this.compToDate = compToDate;
	}

	public Date getToDate() {
		return toDate;
	}

	public void setToDate(Date toDate) {
		this.toDate = toDate;
	}

	public boolean isDisabled() {
		return disabled;
	}

	public void setDisabled(boolean disabled) {
		this.disabled = disabled;
	}

	public void setServiceLocator(ServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}
}

